package org.example.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.example.context.BaseContext;
import org.example.properties.JwtProperties;
import org.example.result.Result;
import org.example.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("当前线程在JWT方法的id:"+Thread.currentThread().getId());

        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)){
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getTokenName());
        Result result = new Result();
        // token为空,未登录时的处理逻辑
        if (token == null || token.isEmpty() || token.equals("{{token}}")) {
            // 返回一个特定的错误响应，比如：令牌缺失或无效
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置为 401
            result.setCode(401);
            result.setData(null);
//            result.setMsg("token为空,未登录");
            result.setMsg("Token is empty, not logged in");
            String json = new ObjectMapper().writeValueAsString(result);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(json);
            return false;
        }

        //2、校验令牌
        try{
            System.out.println("jwt检验："+token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            System.out.println(claims);
            String role = claims.get("role").toString();
            String id;
            id = claims.get("id").toString();

            //设置上下文
            BaseContext.setCurrentId(id);
            BaseContext.setCurrentRole(role);

            //通过，放行
            return true;
        } catch (Exception ex){
            //4、不通过，响应401状态码，token失效
            result.setCode(401);
            result.setData(null);
//            result.setMsg("token失效");
            result.setMsg("Token expiration");
            String json = new ObjectMapper().writeValueAsString(result);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(json);
            return false;
        }
    }

    //清理线程
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.clear();
    }
}
